<?php

/**
 * 
 * pm类
 * @author uglyalien
 *
 */

class pmmodel {

	
	function pmmodel() {
	}

	function pmintval($pmid) {
		return @is_numeric($pmid) ? $pmid : 0;
	}

	/**
	 * 
	 * 根据该条短信的ID返回其他信息，用于在列表页快速回复某一条信息时获取收信人信息
	 * @param int $uid
	 * @param int $pmid
	 */
	function get_pm_by_pmid($uid, $pmid) {
		$arr = DB::fetch_all("SELECT * FROM ".DB::t('u_pms')." WHERE pmid='$pmid' AND (msgtoid IN ('$uid','0') OR msgfromid='$uid')");
		return $arr;
	}

	/**
	 * 
	 * 获取所有确定两人间的所有对话
	 * @param int $uid
	 * @param int $touid
	 * @param int $starttime
	 * @param int $endtime
	 */
	function get_pm_by_touid($uid, $touid, $starttime, $endtime) {
		$arr1 = DB::fetch_all("SELECT * FROM ".DB::t('u_pms')." WHERE msgfromid='$uid' AND msgtoid='$touid' AND dateline>='$starttime' AND dateline<'$endtime' AND related>'0' AND delstatus IN (0,2) ORDER BY dateline");
		$arr2 = DB::fetch_all("SELECT * FROM ".DB::t('u_pms')." WHERE msgfromid='$touid' AND msgtoid='$uid' AND dateline>='$starttime' AND dateline<'$endtime' AND related>'0' AND delstatus IN (0,1) ORDER BY dateline");
		$arr = array_merge($arr1, $arr2);
		uasort($arr, 'pm_datelinesort');
		return $arr;
	}

	/**
	 * 
	 * 获取某个单条信件数据
	 * @param int $uid
	 * @param int $pmid
	 * @param int $type
	 */
	function get_pmnode_by_pmid($uid, $pmid, $type = 0) {
		$arr = array();
		if($type == 1) {
			$arr = DB::fetch_first("SELECT * FROM ".DB::t('u_pms')." WHERE msgfromid='$uid' ORDER BY dateline DESC LIMIT 1");
		} elseif($type == 2) {
			$arr = DB::fetch_first("SELECT * FROM ".DB::t('u_pms')." WHERE msgtoid='$uid' ORDER BY dateline DESC LIMIT 1");
		} else {
			$arr = DB::fetch_first("SELECT * FROM ".DB::t('u_pms')." WHERE pmid='$pmid'");
		}
		return $arr;
	}

	/**
	 * 
	 * 标记信件已读状态，在列表也可以标记所有某人间的，信件页可以标记单个信件
	 * @param int $uid
	 * @param array $touid
	 * @param array $pmid
	 * @param int $status
	 */
	function set_pm_status($uid, $touid, $pmid = 0, $status = 0) {
		if(!$status) {
			$oldstatus = 1;
			$newstatus = 0;
		} else {
			$oldstatus = 0;
			$newstatus = 1;
		}
		if($touid) {
			$ids = is_array($touid) ? dimplode($touid, 0) : $touid;
			DB::exec("UPDATE ".DB::t('u_pms')." SET new='$newstatus' WHERE msgfromid IN ($ids) AND msgtoid='$uid' AND new='$oldstatus'");
		}
		if($pmid) {
			$ids = is_array($pmid) ? dimplode($pmid, 0) : $pmid;
			DB::exec("UPDATE ".DB::t('u_pms')." SET new='$newstatus' WHERE pmid IN ($ids) AND msgtoid='$uid' AND new='$oldstatus'");
		}
	}

	/**
	 * 
	 * 获取列表页信件的总数
	 * @param int $uid
	 * @param char $folder
	 * @param char $filter
	 */
	function get_num($uid, $folder, $filter = '') {
		switch($folder) {
			case 'newbox':
				$sql = "SELECT count(*) FROM ".DB::t('u_pms')." WHERE msgtoid='$uid' AND (related='0' AND msgfromid>'0' OR msgfromid='0') AND new='1'";
				$num = DB::result_first($sql);
				return $num;
			case 'outbox':
			case 'inbox':
				if($filter == 'newpm') {
					$filteradd = "msgtoid='$uid' AND (related='0' AND msgfromid>'0' OR msgfromid='0') AND new='1'";
				} elseif($filter == 'systempm') {
					$filteradd = "msgtoid='$uid' AND msgfromid='0'";
				} elseif($filter == 'privatepm') {
					$filteradd = "msgtoid='$uid' AND related='0' AND msgfromid>'0'";
				} elseif($filter == 'announcepm') {
					$filteradd = "msgtoid='0'";
				} else {
					$filteradd = "msgtoid='$uid' AND related='0'";
				}
				$sql = "SELECT count(*) FROM ".DB::t('u_pms')." WHERE $filteradd";
				break;
			case 'savebox':
				break;
		}
		$num = DB::result_first($sql);
		return $num;
	}

	/**
	 * 
	 * 获取信件列表的内容
	 * @param int $uid
	 * @param int $pmnum
	 * @param char $folder
	 * @param char $filter
	 * @param int $page
	 * @param int $ppp 每页条数
	 */
	function get_pm_list($uid, $folder, $filter, $page, $ppp = 10) {
		$array = array();
		$count = self::get_num($uid, $folder, $filter);
		$array['page'] = prepage($page, $ppp, $count);
		$start = $array['page']['offset'];
		$ppp = $ppp ? $ppp : 10;
		switch($folder) {
			case 'newbox':
				$folder = 'inbox';
				$filter = 'newpm';
			case 'outbox':
			case 'inbox':
				if($filter == 'newpm') {
					$filteradd = "pm.msgtoid='$uid' AND (pm.related='0' AND pm.msgfromid>'0' OR pm.msgfromid='0') AND pm.new='1'";
				} elseif($filter == 'systempm') {
					$filteradd = "pm.msgtoid='$uid' AND pm.msgfromid='0' ";
				} elseif($filter == 'privatepm') {
					$filteradd = "pm.msgtoid='$uid' AND pm.related='0' AND pm.msgfromid>'0'";
				} elseif($filter == 'announcepm') {
					$filteradd = "pm.msgtoid='0'";
				} else {
					$filteradd = "pm.msgtoid='$uid' AND pm.related='0'";
				}
				$sql = "SELECT pm.*,m.username as msgfrom FROM ".DB::t('u_pms')." pm
					LEFT JOIN ".DB::t('u_members')." m ON pm.msgfromid = m.uid
					WHERE $filteradd ORDER BY pm.dateline DESC LIMIT $start, $ppp";
				break;
			case 'searchbox':
				$filteradd = "msgtoid='$uid' AND message LIKE '%".(str_replace('_', '\_', addcslashes($filter, '%_')))."%'";
				$sql = "SELECT * FROM ".DB::t('u_pms')."
					WHERE $filteradd ORDER BY dateline DESC LIMIT $start, $ppp";
				break;
			case 'savebox':
				break;
		}
		
		$query = DB::query($sql);
		while($data = DB::fetch($query)) {
			$data['subject'] = cutstr(htmlspecialchars($data['subject']), 80, '');
			$data['message'] = cutstr($data['message'], 80);
			if($filter == 'announcepm') {
				unset($data['msgfromid'], $data['msgfrom']);
			}
			$data['touid'] = $uid == $data['msgfromid'] ? $data['msgtoid'] : $data['msgfromid'];
			$array['data'][] = $data;
		}
		if($folder == 'inbox') {
			DB::exec("DELETE FROM ".DB::t('u_newpm')." WHERE uid='$uid'");
		}
		return $array;
	}
	
	/**
	 * 
	 * 发送新信息
	 * @param char $subject
	 * @param char $message
	 * @param array $msgfrom
	 * @param int $msgto
	 * @param int $related 为0的时候代表未存在session，需要一个标题
	 */
	function sendpm($subject, $message, $msgfrom, $msgto, $related = 0) {
		if($msgfrom['uid'] && $msgfrom['uid'] == $msgto) return 0;
		$message_notnull = trim($message);
		if($message_notnull == '') return -1;

		$subject = trim($subject);
		if($subject == '' && !$related) {
			$subject = cutstr(trim($message), 75, ' ');
		} else {
			$subject = cutstr(trim($subject), 75, ' ');
		}

		//如果来自非系统，首先判断是否存在过聊天状态，必须保证ralated为1，还必须保证有1个related为0的作为最近一条留言做列表。
		if($msgfrom['uid']) {
			//检测聊天状态
			$sessionexist = DB::result_first("SELECT count(*) FROM ".DB::t('u_pms')." WHERE msgfromid='$msgfrom[uid]' AND msgtoid='$msgto' AND related='0'");
			if(!$sessionexist || $sessionexist > 1) {
				if($sessionexist > 1) {
					DB::exec("DELETE FROM ".DB::t('u_pms')." WHERE msgfromid='$msgfrom[uid]' AND msgtoid='$msgto' AND related='0'");
				}
				DB::exec("INSERT INTO ".DB::t('u_pms')." (msgfrom,msgfromid,msgtoid,new,subject,dateline,related,message) VALUES
					('".$msgfrom['username']."','".$msgfrom['uid']."','$msgto','1','$subject','".TIMESTAMP."','0','$message')");
				$lastpmid = DB::insert_id();
			} else {
				DB::exec("UPDATE ".DB::t('u_pms')." SET subject='$subject', message='$message', dateline='".TIMESTAMP."', new='1' 
					WHERE msgfromid='$msgfrom[uid]' AND msgtoid='$msgto' AND related='0'");
			}
			$sessionexist = DB::result_first("SELECT count(*) FROM ".DB::t('u_pms')." WHERE msgfromid='$msgto' AND msgtoid='$msgfrom[uid]' AND related='0'");
			if($msgfrom['uid'] && !$sessionexist) {
				DB::exec("INSERT INTO ".DB::t('u_pms')." (msgfrom,msgfromid,msgtoid,new,subject,dateline,related,message) VALUES
					('".$msgfrom['username']."','$msgto','".$msgfrom['uid']."','0','$subject','".TIMESTAMP."','0','$message')");
			}
			DB::exec("INSERT INTO ".DB::t('u_pms')." (msgfrom,msgfromid,msgtoid,new,subject,dateline,related,message) VALUES
				('".$msgfrom['username']."','".$msgfrom['uid']."','$msgto','1','$subject','".TIMESTAMP."','1','$message')");
			$lastpmid = DB::insert_id();
		} else {
			DB::exec("INSERT INTO ".DB::t('u_pms')." (msgfrom,msgfromid,msgtoid,new,subject,dateline,related,message) VALUES
				('".$msgfrom['username']."','".$msgfrom['uid']."','$msgto','1','$subject','".TIMESTAMP."','0','$message')");
			$lastpmid = DB::insert_id();
		}
		DB::exec("REPLACE INTO ".DB::t('u_newpm')." (uid) VALUES ('$msgto')");
		return $lastpmid;
	}

	/**
	 * 
	 * 删除本次的提醒，但是有新信到达时，提醒仍将再次出现
	 * @param $uid
	 */
	function set_ignore($uid) {
		DB::exec("DELETE FROM ".DB::t('u_newpm')." WHERE uid='$uid'");
	}

	/**
	 * 
	 * 检查新信息
	 * @param int $uid
	 * @param int $more 0，返回总条数，1，区分私人信息，2，区分系统和公告，3，显示最后一条内容
	 */
	function check_newpm($uid, $more) {
		if($more < 2) {
			$newpm = DB::result_first("SELECT count(*) FROM ".DB::t('u_newpm')." WHERE uid='$uid'");
			if($newpm) {
				$newpm = DB::result_first("SELECT count(*) FROM ".DB::t('u_pms')." WHERE (related='0' AND msgfromid>'0' OR msgfromid='0') AND msgtoid='$uid' AND new='1'");
				if($more) {
					$newprvpm = DB::result_first("SELECT count(*) FROM ".DB::t('u_pms')." WHERE related='0' AND msgfromid>'0' AND msgtoid='$uid' AND new='1'");
					return array('newpm' => $newpm, 'newprivatepm' => $newprvpm);
				} else {
					return $newpm;
				}
			}
		} else {
			$newpm = DB::result_first("SELECT count(*) FROM ".DB::t('u_pms')." WHERE (related='0' AND msgfromid>'0' OR msgfromid='0') AND msgtoid='$uid' AND new='1'");
			$newprvpm = DB::result_first("SELECT count(*) FROM ".DB::t('u_pms')." WHERE related='0' AND msgfromid>'0' AND msgtoid='$uid' AND new='1'");
			if($more == 2 || $more == 3) {
				$annpm = DB::result_first("SELECT count(*) FROM ".DB::t('u_pms')." WHERE related='0' AND msgtoid='0' ");
				$syspm = DB::result_first("SELECT count(*) FROM ".DB::t('u_pms')." WHERE related='0' AND msgtoid='$uid' AND msgfromid='0'");
			}
			if($more == 2) {
				return array('newpm' => $newpm, 'newprivatepm' => $newprvpm, 'announcepm' => $annpm, 'systempm' => $syspm);
			} if($more == 4) {
				return array('newpm' => $newpm, 'newprivatepm' => $newprvpm);
			} else {
				$pm = DB::fetch_first("SELECT pm.dateline,pm.msgfromid,m.username as msgfrom,pm.message FROM ".DB::t('u_pms')." pm LEFT JOIN ".DB::t('u_members')." m ON pm.msgfromid = m.uid WHERE (pm.related='0' OR pm.msgfromid='0') AND pm.msgtoid='$uid' ORDER BY pm.dateline DESC LIMIT 1");
				return array('newpm' => $newpm, 'newprivatepm' => $newprvpm, 'announcepm' => $annpm, 'systempm' => $syspm, 'lastdate' => $pm['dateline'], 'lastmsgfromid' => $pm['msgfromid'], 'lastmsgfrom' => $pm['msgfrom'], 'lastmsg' => $pm['message']);
			}
		}
	}

	/**
	 * 
	 * 只能删除发给自己的信息
	 * @param int $uid
	 * @param array $pmids
	 * @return Int affected_rows
	 */
	function deletepm($uid, $pmids) {
		return DB::exec("DELETE FROM ".DB::t('u_pms')." WHERE msgtoid='$uid' AND pmid IN (".dimplode($pmids, 0).")");
	}

	/**
	 * 
	 * 删除与某些人之间的所有信件，因为这些信件能被两人同时查到，所以存在一个del状态，只有两人都删除的情况下才能被真正删除！
	 * @param $uid
	 * @param $ids
	 */
	function deleteuidpm($uid, $ids) {
		$delnum = 0;
		if($ids) {
			$delnum = 1;
			$deluids = dimplode($ids, 0);
			DB::exec("DELETE FROM ".DB::t('u_pms')."
				WHERE msgfromid IN ($deluids) AND msgtoid='$uid' AND related='0'");
			DB::exec("UPDATE ".DB::t('u_pms')." SET delstatus=2
				WHERE msgfromid IN ($deluids) AND msgtoid='$uid' AND delstatus=0");
			DB::exec("UPDATE ".DB::t('u_pms')." SET delstatus=1
				WHERE msgtoid IN ($deluids) AND msgfromid='$uid' AND delstatus=0");
			DB::exec("DELETE FROM ".DB::t('u_pms')."
				WHERE msgfromid IN ($deluids) AND msgtoid='$uid' AND delstatus=1 ");
			DB::exec("DELETE FROM ".DB::t('u_pms')."
				WHERE msgtoid IN ($deluids) AND msgfromid='$uid' AND delstatus=2 ");
		}
		return $delnum;
	}

}

function pm_datelinesort($a, $b) {
	if ($a['dateline'] == $b['dateline']) {
		return 0;
	}
	return ($a['dateline'] < $b['dateline']) ? -1 : 1;
}